import 'dart:convert';

import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:jpush_flutter/jpush_flutter.dart';
import 'package:sui_shou_pai/chat/chat_room.dart';
import 'package:sui_shou_pai/chat/entity/chat_record.dart';
import 'package:sui_shou_pai/chat/entity/message_model.dart';
import 'package:sui_shou_pai/chat/init/init_map.dart';
import 'package:sui_shou_pai/chat/init/interface.dart';
import 'package:sui_shou_pai/module/effect.dart';

class MessageList extends StatefulWidget {
  @override
  _MessageListState createState() {
    return _MessageListState();
  }
}

class _MessageListState extends State<MessageList> {
  List<MessageModel> messages = []; //沟通记录列表

  JPush jPush = InitMap.jPush;

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    messages = InitMap.messageMap.values.toList();
    initPlatFormState();
  }

  Future<Null> _handleRefresh() async {
    // 模拟数据的延迟加载
    InitMap.initGlobalMap();
    await Future.delayed(Duration(seconds: 1), () {
      setState(() {
        messages = InitMap.messageMap.values.toList();
      });
    });
  }

  /// 获取最后一条消息内容
  String getLastRecordContent(String id) {
    List<ChatRecord> records = InitMap.recordsMap[id];
    if (records != null && records.isNotEmpty) {
      if (id == "9") {
        return getRealContent(records.first.content);
      } else {
        return records.first.content;
      }
    } else {
      return "";
    }
  }

  String getRealContent(String content) {
    int index = 0;
    for (int i = 0; i < content.length; i++) {
      if (content[i] == '#') {
        index = i;
      }
    }
    return content.substring(index + 1, content.length);
  }

  /// 获取最后一条消息时间
  String getLastRecordTime(String id) {
    List<ChatRecord> records = InitMap.recordsMap[id];
    if (records != null && records.isNotEmpty) {
      return records.first.time.substring(0, 10);
    } else {
      return "";
    }
  }

  /// 极光推送
  Future<void> initPlatFormState() async {
    String platform = "";

    try {
      jPush.addEventHandler(
          onReceiveNotification: (Map<String, dynamic> message) async {
        String content = message["alert"];
        var json = jsonDecode(message["extras"]["cn.jpush.android.EXTRA"]);
        _handleRefresh();
      }, onOpenNotification: (Map<String, dynamic> message) async {
        print("通过点击推送进入app：$message");
      }, onReceiveMessage: (Map<String, dynamic> message) async {
        print("接收到自定义消息：$message");
      }, onReceiveNotificationAuthorization:
              (Map<String, dynamic> message) async {
        print("通知权限发生变更：$message");
      });
    } on PlatformException {
      platform = "平台版本获取失败";
    }
  }

  @override
  Widget build(BuildContext context) {
    return RefreshIndicator(
      child: ListView.builder(
        itemCount: messages.length,
        itemBuilder: (context, index) {
          if (getLastRecordContent(messages[index].id) != "") {
            return Container(
              decoration: BoxDecoration(
                color: Colors.white,
                borderRadius: borderRadiusAll8(),
                boxShadow: [shadowOffsetY2()],
              ),
              margin: EdgeInsets.fromLTRB(12, 12, 12, 0),
              padding: EdgeInsets.symmetric(vertical: 8),
              child: ListTile(
                  title: Row(
                    children: <Widget>[
                      //员工头像
                      Container(
                        width: 60,
                        height: 60,
                        decoration: BoxDecoration(
                          borderRadius: borderRadiusAll40(),
                          image: DecorationImage(
                              fit: BoxFit.cover,
                              image: NetworkImage(messages[index].avatar)),
                        ),
                      ),
                      Expanded(
                          child: Row(
                        mainAxisAlignment: MainAxisAlignment.spaceBetween,
                        children: <Widget>[
                          Container(
                            height: 60,
                            margin: EdgeInsets.only(left: 15.0),
                            child: Column(
                              mainAxisAlignment: MainAxisAlignment.spaceAround,
                              crossAxisAlignment: CrossAxisAlignment.start,
                              children: <Widget>[
                                Text(
                                  messages[index].name,
                                  style: TextStyle(
                                      fontSize: 18.0,
                                      fontWeight: FontWeight.bold),
                                ),
                                Text(
                                  getLastRecordContent(messages[index].id),
                                  maxLines: 1,
                                  overflow: TextOverflow.ellipsis,
                                  style: TextStyle(
                                      fontSize: 14.0, color: Colors.grey),
                                ),
                              ],
                            ),
                          ),
                          Container(
                              height: 60,
                              child: Column(
                                mainAxisAlignment:
                                    MainAxisAlignment.spaceAround,
                                crossAxisAlignment: CrossAxisAlignment.end,
                                children: <Widget>[
                                  Text(
                                    getLastRecordTime(messages[index].id),
                                    style: TextStyle(
                                        fontSize: 14.0, color: Colors.grey),
                                  ),
                                  NumWidget(
                                    num: messages[index].num,
                                  ),
                                ],
                              )),
                        ],
                      ))
                    ],
                  ),
                  //点击跳转到聊天室
                  onTap: () {
                    setState(() {
                      if (messages[index].num != "0") {
                        if (messages[index].id != "9") {
                          messages[index].setNum("0");
                          ChatInterface.changeIsread(messages[index].id);
                        }
                      }
                    });
                    Navigator.push(
                        context,
                        //push跳转页面时，通过构造方法传递数据
                        MaterialPageRoute(
                          builder: (context) => ChatRoom(
                            id: messages[index].id,
                            name: messages[index].name,
                            avatar: messages[index].avatar,
                          ),
                        ));
                  }),
            );
          } else {
            return Container(height: 0.0);
          }
        },
      ),
      onRefresh: _handleRefresh,
    );
  }
}

/// 未读条数组件
class NumWidget extends StatefulWidget {
  final String num;

  const NumWidget({Key key, @required this.num}) : super(key: key);

  @override
  NumWidgetState createState() {
    return NumWidgetState();
  }
}

class NumWidgetState extends State<NumWidget> {
  @override
  Widget build(BuildContext context) {
    if (widget.num != "0") {
      return Container(
          alignment: Alignment.bottomCenter,
          child: Container(
            alignment: Alignment.center,
            decoration: BoxDecoration(
              borderRadius: borderRadiusAll40(),
              color: Colors.redAccent,
            ),
            width: 16.0,
            height: 16.0,
            child: Text(
              widget.num.toString(),
              style: TextStyle(color: Colors.white, fontSize: 10.0),
            ),
          ));
    }
    //如果数量为0，则不显示
    else {
      return Container();
    }
  }
}
